package v1

import (
	"fmt"
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

//新增category
func AddCategory(c *gin.Context) {
	var category model.Category
	err := c.ShouldBindJSON(&category)
	if err != nil {
		fmt.Println("xxxxxxx: ", err)
	}
	code := model.CheckCategoryName(category.Name)
	if code == errmsg.SUCCESS {
		codeUpdate := model.AddCategory(&category)
		if codeUpdate == errmsg.SUCCESS {
			c.JSON(http.StatusOK, gin.H {
				"code":code,
				"message":errmsg.GetErrorMsg(codeUpdate),
			})
		}
	} else {
		c.JSON(http.StatusOK, gin.H {
			"code":code,
			"message":errmsg.GetErrorMsg(code),
		})
	}
}

//查询categorys
func GetCategorys(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	fmt.Println("pageSize pageNum is : ", pageSize, pageNum)
	data, code := model.GetCategorys(pageSize, pageNum)
	if code == errmsg.SUCCESS {
		c.JSON(http.StatusOK, gin.H {
			"code":code,
			"data":data,
			"message":errmsg.GetErrorMsg(code),
		})
	}
	if code == errmsg.ERROR {
		c.JSON(http.StatusOK, gin.H {
			"code":code,
			"message":errmsg.GetErrorMsg(code),
		})
	}
}

//根据id查询category
func GetCategoryById(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	data, code := model.GetCategoryById(id)
	if code == errmsg.SUCCESS {
		c.JSON(http.StatusOK, gin.H {
			"code":code,
			"data":data,
			"message":errmsg.GetErrorMsg(code),
		})
	}

}

//根据id删除用户
func DeleteCategoryById(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DeleteCategoryById(id)
	c.JSON(http.StatusOK, gin.H {
		"code":code,
		"message":errmsg.GetErrorMsg(code),
	})
}

//编辑category
func EditCategoryById(c *gin.Context) {
	var data model.Category
	id, _ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&data)
	code := model.EditCategiryById(id, data)
	c.JSON(http.StatusOK, gin.H {
		"code":code,
		"message":errmsg.GetErrorMsg(code),
	})
}












